package cn.ffcs.uec.outStaff.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.outStaff.component.bean.UecOutStaffPartyLogListboxBean;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.staff.manager.UecPartyLogManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecPartyLog;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import cn.ffcs.uom.common.zul.PubUtil;
import lombok.Getter;
import lombok.Setter;

@Controller
@Scope("prototype")
public class UecOutStaffPartyLogListboxExt extends Div implements IdSpace {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6487871788980086081L;
	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	@Getter
	private UecOutStaffPartyLogListboxBean bean = new UecOutStaffPartyLogListboxBean();
	/**
	 * 人员政治面貌实体
	 */
	private UecPartyLog uecPartyLog;

	/**
	 * 翻页查询条件实体
	 */
	private UecPartyLog partyLogPaging;

	private UecPartyLog approvalPartyLogPaging;

	private List<UecPartyLog> partyLogList = new ArrayList<UecPartyLog>();

	private boolean isOutStaffEntryExt = false;

	private UecPartyLogManager uecPartyLogManager = (UecPartyLogManager) ApplicationContextUtil
			.getBean("uecPartyLogManager");

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutStaffPartyLogListboxExt() {
		Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_PARTYLOG_EXT_LISTBOX_ZUL,
				this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.addForward(UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY_OF_OUTSTAFF_ENTRY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY_OF_OUTSTAFF_ENTRY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY_OF_OUTSTAFF_ENTRY_VIEW,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_PARTYLOG_QUERY_OF_OUTSTAFF_ENTRY_VIEW_RESPONSE);

		this.addForward(UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_PARTYLOG,
				this,
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_PARTYLOG_RESPONSE);

	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 选择查询记录
	 * 
	 * @throws Exception
	 */
	public void onSelectUecPartyLogList() throws Exception {
		if (this.bean.getUecPartyLogListbox().getSelectedCount() > 0) {
			uecPartyLog = (UecPartyLog) bean.getUecPartyLogListbox()
					.getSelectedItem().getValue();
		}
	}

	/**
	 * ，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffPartyLogQueryResponse(ForwardEvent event) {
		uecOutStaffInfo = (UecOutStaffInfo) event.getOrigin().getData();
		if (null != uecOutStaffInfo) {
	        //设置操作按钮，非盟市主管不可操作按钮
	        if(PermissionUtil.isNoMainOutStaff()) {
	            this.setButtonValid(false, false, false, false);
	        }else {
	            this.setButtonValid(true, true, true, false);
	        }
			UecPartyLog uecPartyLogObj = new UecPartyLog();
			uecPartyLogObj.setStaffId(uecOutStaffInfo.getOutStaffId());
			uecPartyLogObj.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			uecPartyLog = uecPartyLogObj;
			partyLogPaging = uecPartyLogObj;		
			this.onQueryUecPartyLog();
		}
	}

	/**
	 * 抛出事件， 事件监听,来自入职审批页
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	public void onUecOutStaffPartyLogQueryOfOutStaffEntryResponse(
			ForwardEvent event) {
		Map<String, Object> map = (Map<String, Object>) event.getOrigin()
				.getData();
		if (null != map) {
			isOutStaffEntryExt = (Boolean) map.get("isOutStaffEntryExt");
			uecOutStaffInfo = (UecOutStaffInfo) map.get("uecOutStaffInfo");
			if (null != uecOutStaffInfo) {
				UecPartyLog uecPartyLogObj = new UecPartyLog();
				uecPartyLogObj.setStaffId(uecOutStaffInfo.getOutStaffId());
				uecPartyLogObj
						.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
				uecPartyLog = uecPartyLogObj;
				this.setButtonValid(true, true, true, false);
				ListModel list = new BindingListModelList(partyLogList, true);
				this.bean.getUecPartyLogListbox().setModel(list);
				this.bean.getUecPartyLogListboxPaging().setTotalSize(1);
				uecPartyLog = null;
			}
		}
	}

	/**
	 * 政治面貌审批信息id，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffPartyLogQueryOfOutStaffEntryViewResponse(
			ForwardEvent event) {
		partyLogList.clear();
		approvalPartyLogPaging = new UecPartyLog();
		String partyLogIds = (String) event.getOrigin().getData();
		if (!StrUtil.isNullOrEmpty(partyLogIds)) {
			String[] partyLogIdArray = partyLogIds.split("-");
			if (!StrUtil.isNullOrEmpty(partyLogIdArray)
					&& partyLogIdArray.length > 0) {
				for (String partyLogId : partyLogIdArray) {
					UecPartyLog uecPartyLog = UecPartyLog.newInstance();
					uecPartyLog.setPartylogId(Long.valueOf(partyLogId));
					uecPartyLog = uecPartyLogManager
							.findUecPartyLogById(uecPartyLog);
					partyLogList.add(uecPartyLog);
				}

				onQueryUecPartyLog();
			}
		}

	}

	/**
	 * 清除
	 * 
	 * @param event
	 */
	public void onCleanUecPartyLogResponse(ForwardEvent event) {
		onCleanUecOutStaffPartylogResponse();
	}

	public void onCleanUecOutStaffPartylogResponse() {
		clearVariable();
		uecOutStaffInfo = null;
		ListboxUtils.clearListbox(this.bean.getUecPartyLogListbox());
		this.bean.getUecPartyLogListboxPaging().setTotalSize(1);

		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canView, boolean canAdd,
			boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);
	}

	/**
	 * 查询按钮
	 */
	public void onQueryUecPartyLog() {
		this.bean.getUecPartyLogListboxPaging().setActivePage(0);
		this.onQueryUecPartyLogList();
	}

	/**
	 * 重置按钮
	 */
	public void onResetUecPartyLog() {
		ListboxUtils.clearListbox(this.bean.getUecPartyLogListbox());
		this.bean.getUecPartyLogListboxPaging().setTotalSize(1);
	}

	/**
	 * 
	 * @param opType
	 */
	private void openUecEditWin(final String opType) {
		// boolean isOnTtrial = isOnTrial();
		// if (!isOnTtrial) {
		// return;
		// }
		if (null != uecOutStaffInfo) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", opType);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			if ("view".equals(opType) || "edit".equals(opType)) {
				if (null != uecPartyLog) {
					map.put("uecPartyLog", uecPartyLog);
				} else {
					ZkUtil.showError("请选择一条记录！", "提示信息");
					return;
				}
			} else if ("add".equals(opType)) {
				map.put("uecOutStaffInfo", uecOutStaffInfo);
			}
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_PARTYLOG_EDIT_ZUL, this,
					map);
			try {
				window.doModal();
				window.addEventListener("onOK", new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (event.getData() != null) {
							if ("edit".equals(opType) && isOutStaffEntryExt) {
								partyLogList.remove(uecPartyLog);
							}
							// 新增或修改完成后，列表从数据库更新
							uecPartyLog = (UecPartyLog) event.getData();
							if (!isOutStaffEntryExt) {
								onQueryUecPartyLogList();
							} else {
								partyLogList.add(uecPartyLog);
								ListModel list = new BindingListModelList(
										partyLogList, true);
								bean.getUecPartyLogListbox().setModel(list);
								bean.getUecPartyLogListboxPaging()
										.setTotalSize(1);

								postPartLogList();
							}

						}
					}
				});
			} catch (SuspendNotAllowedException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onViewUecPartyLog() throws Exception, InterruptedException {
		if (uecPartyLog != null) {
			openUecEditWin("view");
		} else {
			ZkUtil.showError("请选中要查看的记录", "提示信息");
			return;
		}

	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecPartyLog() throws Exception {
		openUecEditWin("add");
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecPartyLog() throws Exception, InterruptedException {
		if (uecPartyLog != null) {
			openUecEditWin("edit");
		} else {
			ZkUtil.showError("请选中要编辑的记录", "提示信息");
			return;
		}
	}

	/**
	 * 审批状态中修改
	 */
	public void onApprovalEditUecPartyLog() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "approvalEdit");
		map.put("isOutStaffEntryExt", isOutStaffEntryExt);
		if (null != uecPartyLog) {
			map.put("uecPartyLog", uecPartyLog);
		} else {
			ZkUtil.showError("请选中要修改的记录！", "提示信息");
			return;
		}
		Window window = (Window) Executions
				.createComponents(
						UecOutStaffConstants.UEC_OUT_STAFF_PARTYLOG_EDIT_ZUL,
						this, map);
		try {
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecPartyLog = (UecPartyLog) event.getData();
						PageInfo pageInfo = uecPartyLogManager
								.queryPageInfoByUecPartyLogOnApproval(
										uecPartyLog, bean
												.getUecPartyLogListboxPaging()
												.getActivePage() + 1, bean
												.getUecPartyLogListboxPaging()
												.getPageSize());
						ListModel list = new BindingListModelList(pageInfo
								.getDataList(), true);
						bean.getUecPartyLogListbox().setModel(list);
						bean.getUecPartyLogListboxPaging().setTotalSize(1);

						uecPartyLog = null;

					}
				}
			});
		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 删除按钮
	 */
	public void onDelUecPartyLog() {
		if (this.uecPartyLog != null && uecOutStaffInfo != null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						// uecPartyLog.setId(id);
						uecPartyLog.removeOnly();
						PubUtil.reDisplayListbox(bean.getUecPartyLogListbox(),
								uecPartyLog, "del");
						uecPartyLog = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 抛出事件，把添加的列表发送给OutStaffEntryExt
	 */
	private void postPartLogList() {
		Events.postEvent("onPostPartyLogListOfOutStaffEntry", this,
				partyLogList);
	}

	/**
	 * 翻页
	 */
	public void onUecOutPartyLogListboxPaging() {
		this.onQueryUecPartyLogList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecPartyLog = null;
		partyLogPaging = null;
		partyLogList.clear();
	}

	/**
	 * 查询
	 */
	public void onQueryUecPartyLogList() {
		// 翻页查看生效数据
		if (null != partyLogPaging) {
			PageInfo pageInfo = uecPartyLogManager.queryPageInfoByUecPartyLog(
					partyLogPaging, this.bean.getUecPartyLogListboxPaging()
							.getActivePage() + 1, this.bean
							.getUecPartyLogListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecPartyLogListbox().setModel(list);
			this.bean.getUecPartyLogListboxPaging().setTotalSize(
					pageInfo.getTotalCount());

		} else {
			cn.ffcs.uom.common.util.PubUtil.clearListbox(bean
					.getUecPartyLogListbox());
		}

		if (null != approvalPartyLogPaging) {
//			List<UecPartyLog> pagePartyLogs = getCurrentPageList(partyLogList, bean
//					.getUecPartyLogListboxPaging().getActivePage() + 1, bean
//					.getUecPartyLogListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(partyLogList, true);
			this.bean.getUecPartyLogListbox().setModel(list);
			this.bean.getUecPartyLogListboxPaging().setTotalSize(1);

		}
		uecPartyLog = null;
	}

	/**
	 * 获取当前页list
	 * 
	 * @param list
	 * @param activePage
	 * @param pageSize
	 * @return
	 */
	public List<UecPartyLog> getCurrentPageList(List<UecPartyLog> list, int activePage,
			int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);

	}

	/**
	 * 判断是否入职
	 * 
	 * @return
	 */
	@SuppressWarnings("unused")
	private boolean isOnTrial() {
		UecTrial qryUecTrial = UecTrial.newInstance();
		qryUecTrial.setStaffId(uecOutStaffInfo.getOutStaffId());
		qryUecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
		if (null == qryUecTrial) {
			ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
			return false;
		}
		return true;
	}

}
